﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace Common.BaseLibrary.Config
{

    public class ConfigManager
    {
        /// <summary>
        /// 模型初始化
        /// </summary>
        private static ConfigModel _init;


        private static ConfigModel _config;
        private static string _fileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, 
            "ConfigConstants.xml");
        private static object _lockObj = new object();

        static ConfigManager()
        {
            _init = new ConfigModel();

            //日志相关
            _init.Logger.Level = "DEBUG";
            _init.Logger.ProjectName = "WYY.Library";
            _init.Logger.Type = "File";

            _init.DomainEvent.Type = "Memory";
            _init.DomainEvent.RedisKey = "DomainEventBus";
            _init.Redis.Host = "localhost:6379";
            _init.Redis.Proxy = 0;
        }


        /// <summary>
        /// 配置字典,单例模式
        /// </summary>
        /// <returns></returns>
        public static ConfigModel Config
        {
            get
            {
                if (_config == null)
                {
                    lock (_lockObj)
                    {
                        XmlElement xml = null;
                        var old = Utils.SerializationHelper.DeserializeFromXml<ConfigModel>(_fileName);
                        if (old != null)
                        {
                            var configXml = new XmlDocument();
                            configXml.Load(_fileName);
                            xml = configXml.DocumentElement;
                        }
                        if (old == null || xml.ChildNodes.Count != typeof(ConfigModel).GetProperties().Count())
                        {
                            _config = _init;
                            Utils.SerializationHelper.SerializeToXml(_fileName, _init);
                        }
                        else
                        {
                            _config = old;
                        }
                    }

                }
                return _config;
            }
        }

    }
}
